﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
namespace PTHTTT_STDT_Demo
{
    public partial class frmketnoi : Form
    {
        public frmketnoi()
        {
            InitializeComponent();
        }
        Server srv;
        ServerConnection connServer;


        private void frmketnoi_Load(object sender, EventArgs e)
        {
            // lay server name tu registry
            RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
            String[] instances = (String[])rk.GetValue("InstalledInstances");
            if (instances.Length > 0)
            {
                foreach (String element in instances)
                {
                    if (element == "MSSQLSERVER")
                        comboBox1.Items.Add(System.Environment.MachineName);
                    else
                        comboBox1.Items.Add(System.Environment.MachineName + @"\" + element);
                }
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //quyen windows
            if (checkBox1.Checked == true)
            {
                comboBox2.Items.Clear();
                SqlConnection conn = new SqlConnection(@"Data Source=" + comboBox1.Text + ";Initial Catalog=master;Integrated Security=True");
                // thu tuc liet ke cac co so du lieu trong sqlserver
                SqlCommand cmmd = new SqlCommand("SP_DATABASES", conn);
                SqlDataReader read;
                try
                {
                    conn.Open();
                    read = cmmd.ExecuteReader();
                    while (read.Read())
                    {
                        comboBox2.Items.Add(read[0].ToString());
                    }
                    comboBox2.Enabled = true;
                    MessageBox.Show("Kết nối thành công", "Succeed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                        cmmd.Dispose();
                    }
                }
            }
            else
            {
                comboBox2.Items.Clear();
                SqlConnection conn = new SqlConnection(@"Data Source=" + comboBox1.Text + ";Initial Catalog=master;User Id=" + textBox1.Text + ";Password=" + textBox2.Text + "");
                // thu tuc liet ke cac co so du lieu trong sqlserver
                SqlCommand cmmd = new SqlCommand("SP_DATABASES", conn);
                SqlDataReader read;
                try
                {
                    conn.Open();
                    read = cmmd.ExecuteReader();
                    while (read.Read())
                    {
                        comboBox2.Items.Add(read[0].ToString());
                    }
                    comboBox2.Enabled = true;
                    MessageBox.Show("Kết nối thành công", "Succeed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                        cmmd.Dispose();
                    }
                }
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                textBox1.Enabled = false;
                textBox2.Enabled = false;
            }
            else
            {
                textBox1.Enabled = true;
                textBox2.Enabled = true;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            button3.Enabled = true;

            if (checkBox1.Checked == true)
            {
                Connect.saveConfig("Server", comboBox1.Text);
                Connect.saveConfig("Database", comboBox2.Text);
                Connect.saveConfig("Username", "");
                Connect.saveConfig("Password", "");
            }
            else
            {
                Connect.saveConfig("Server", comboBox1.Text);
                Connect.saveConfig("Database", comboBox2.Text);
                Connect.saveConfig("Username", textBox1.Text);
                Connect.saveConfig("Password", textBox2.Text);
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {

            OpenFileDialog openFile = new OpenFileDialog();
            openFile.InitialDirectory = "c:\\";
            openFile.Filter = "bak files(*.bak)|*.bak|All files(*.*)|*.*";
            openFile.FilterIndex = 2;
            openFile.RestoreDirectory = true;
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                textBox3.Text = openFile.FileName.ToString();

            }
        }

        private void textBox4_Leave(object sender, EventArgs e)
        {

        }

        private void textBox3_Leave(object sender, EventArgs e)
        {

            StreamWriter objStreamWriter = new StreamWriter(@"""");
        }

        private void button3_Click(object sender, EventArgs e)
        {


            if (textBox3.Text == "")
            {
                MessageBox.Show("Chọn đường dẫn lưu tập tin", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            if (textBox4.Text == "")
            {
                MessageBox.Show("Nhập tên file cần sao lưu", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Backup bkp = new Backup();
            this.Cursor = Cursors.WaitCursor;
            if (checkBox1.Checked == true)
            {
                connServer = new ServerConnection();
                connServer.ServerInstance = comboBox1.Text;
            }
            else
            {
                connServer = new ServerConnection(comboBox1.Text, textBox1.Text, textBox2.Text);
            }
            srv = new Server(connServer);
            try
            {
                string fileName = textBox3.Text;
                string database = comboBox2.SelectedItem.ToString();
                bkp.Action = BackupActionType.Database;
                bkp.Database = database;
                bkp.Devices.AddDevice(fileName, DeviceType.File);
                bkp.Incremental = checkBox2.Checked;
                progressBar1.Value = 0;
                progressBar1.Maximum = 100;
                progressBar1.Value = 10;
                bkp.PercentCompleteNotification = 10;
                bkp.PercentComplete += new PercentCompleteEventHandler(progressEventHandler);
                bkp.SqlBackup(srv);
                MessageBox.Show("Sao luu thanh cong", "Thong bao", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            finally
            {
                this.Cursor = Cursors.Default;
                progressBar1.Value = 0;
            }
        }
        public void progressEventHandler(object sender, PercentCompleteEventArgs e)
        {
            progressBar1.Value = e.Percent;
        }
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBox4.Text = comboBox2.Text + ".bak";
            textBox3.Text = @"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup" + @"\" + textBox4.Text;
        }

        private void button7_Click(object sender, EventArgs e)
        {
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (textBox3.Text == "")
            {
                MessageBox.Show("Chọn đường dẫn lưu tập tin", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            if (textBox4.Text == "")
            {
                MessageBox.Show("Nhập tên file cần phục hồi", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Restore res = new Restore();
            this.Cursor = Cursors.WaitCursor;
            if (checkBox1.Checked == true)
            {
                connServer = new ServerConnection();
                connServer.ServerInstance = comboBox1.Text;
            }
            else
            {
                connServer = new ServerConnection(comboBox1.Text, textBox1.Text, textBox2.Text);
            }
            srv = new Server(connServer);
            try
            {
                string fileName = textBox3.Text;
                string database = comboBox2.SelectedItem.ToString();
                res.Action = RestoreActionType.Database;
                res.Database = database;
                res.Devices.AddDevice(fileName, DeviceType.File);
               
                progressBar1.Value = 0;
                progressBar1.Maximum = 100;
                progressBar1.Value = 10;
                res.PercentCompleteNotification = 10;
                res.PercentComplete += new PercentCompleteEventHandler(progressEventHandler);
                res.SqlRestore(srv);
                MessageBox.Show("Phục hồi thành công", "Thong bao", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            finally
            {
                this.Cursor = Cursors.Default;
                progressBar1.Value = 0;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Connect obj = new Connect();
            SqlConnection conn = obj.get_Connect();
            DataSet ds = new DataSet();
            try
            {
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter("restore filelistonly from disk='" + textBox3.Text + "'", conn);
                da.Fill(ds, "table");
                dataGridView1.DataSource = ds.Tables["table"];
                MessageBox.Show("Hiển thị chi tiết thành công");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
    }
}
  
    

